package com.rykj.base;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gyf.immersionbar.ImmersionBar;
import com.rykj.R;
import com.rykj.util.CommonUtil;
import com.rykj.util.LogX;
import com.rykj.widget.TopBar;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


/**
 * Description: author: zhangsan on 16/11/21 上午9:28.
 */

public abstract class BaseActivity extends AppCompatActivity implements TipCommonMvpView, TopBar.onTopBarClickListener {

    protected String TAG = getClass().getSimpleName();

    protected Context mContext;


    protected LoadingDialogHelper loadingDialogHelper;

    protected <T extends View> T getView(int viewId) {
        return (T) findViewById(viewId);
    }

    protected <T extends View> T getViewFromLayout(@LayoutRes int layout) {
        return getViewFromLayout(layout, null, false);
    }

    protected <T extends View> T getViewFromLayout(@LayoutRes int layout, ViewGroup root, boolean attach) {
        return (T) LayoutInflater.from(mContext).inflate(layout, root, attach);
    }

    protected <T extends View> T getViewFromLayout(@LayoutRes int layout, @IdRes int viewId) {
        View v = LayoutInflater.from(mContext).inflate(layout, null, false);
        return (T) v.findViewById(viewId);
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        loadingDialogHelper = new LoadingDialogHelper();
        mContext = this;
        setContentView(getLayoutId());
        if (eventBusEnable()) {
            registerBus();
        }
        if (immersionEnable()) {
            immersionBar().init();
        }
        TopBar topBar = findViewById(R.id.topbar);
        if (topBar != null) {
            topBar.setTopBarClickListener(this);
        }
        initView(bundle);
    }

    protected void initView(Bundle bundle) {

    }

    protected abstract int getLayoutId();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mContext = null;
        if (eventBusEnable()) {
            unRegisterBus();
        }
    }

    public static boolean isActive; //全局变量

    @Override
    protected void onResume() {
        if (!isActive) {
            //app 从后台唤醒，进入前台
            isActive = true;
            LogX.e("测试", "程序从后台唤醒");
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        if (!isAppOnForeground()) {
            //app 进入后台
            isActive = false;//记录当前已经进入后台
            LogX.e("测试", "程序进入后台");
        }
        super.onStop();
    }

    /**
     * APP是否处于前台唤醒状态
     */
    public boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * show to @param(cls)
     */
    public void showActivity(Intent it) {
        startActivity(it);
    }

    /**
     * show to @param(cls)
     */
    public void showActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent(mContext, cls);
        intent.putExtras(extras);
        startActivity(intent);
    }

    /**
     * skip to @param(cls), and this finish() method
     */
    public void skipActivity(Class<?> cls) {
        showActivity(cls);
        finish();
    }

    /**
     * show to @param(cls)
     */
    public void showActivity(Class<?> cls) {
        Intent intent = new Intent(mContext, cls);
        startActivity(intent);
    }

    /**
     * 启动包名的    activity
     */
    public void showActivity(String packageName, String clasName) {
        Intent i = new Intent();
        i.setClassName(packageName, clasName);
        startActivity(i);
    }

    public void showActivity(String clasName) {
        Intent i = new Intent();
        i.setClassName(mContext, clasName);
        startActivity(i);
    }

    protected void registerBus() {
        EventBus.getDefault().register(this);
    }

    protected void unRegisterBus() {
        EventBus.getDefault().unregister(this);
    }

    protected void showLoading() {
        showLoading(R.string.in_load);
    }

    public void showToast(@StringRes int tip) {
        showToast(mContext.getResources().getString(tip));
    }

    @Override
    public void showToast(String msg) {
        CommonUtil.showToast(msg);
    }

    @Override
    public void showLoading(String msg) {
        loadingDialogHelper.showLoading(this, msg);
    }

    @Override
    public void showLoading(int msg) {
        loadingDialogHelper.showLoading(this, msg);
    }

    @Override
    public void disMissLoading() {
        loadingDialogHelper.disMiss();
    }

    @Override
    public Context getContext() {
        return this;
    }


    @Override
    public void onTopBarViewClick(View v) {
        int id = v.getId();
        if (id == R.id.topBarImgBtnLeft) {
            onTopBarLeftImgClick();
        } else if (id == R.id.topBarTitle) {
            onTopBarTitleClick();
        } else if (id == R.id.topBarImgBtnRight) {
            onTopBarRightImgClick();
        } else if (id == R.id.topBarTvRight) {
            onTopBarRightTextClick();
        }
    }

    /**
     * topbar 左边imagebtn 点击响应
     */
    public void onTopBarLeftImgClick() {
        finish();
    }

    /**
     * topbar 右边imagebtn 点击响应
     */
    public void onTopBarRightImgClick() {

    }

    /**
     * desc: 右边TextView点击响应
     **/
    public void onTopBarRightTextClick() {

    }

    /**
     * topbar 中间 文本 点击响应
     */
    public void onTopBarTitleClick() {

    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    public void initPermission() {
        String[] permissions = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE // demo使用
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 此处为android 6.0以上动态授权的回调，用户自行实现。
    }

    public boolean immersionEnable() {
        return true;
    }

    public boolean eventBusEnable() {
        return false;
    }

    public ImmersionBar immersionBar() {
        return ImmersionBar.with(this).titleBar(findViewById(R.id.topbar)).statusBarDarkFont(true).autoStatusBarDarkModeEnable(true);
    }
}
